package com.ruoyi.project.bajiaostar.user;


import com.alibaba.excel.EasyExcel;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.framework.aop.UserRepeatSubmit;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.listener.entity.ImportGoodDto;
import com.ruoyi.framework.listener.entity.UpdateImportExcelDto;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.bajiaostar.tGood.domain.TGood;
import com.ruoyi.project.bajiaostar.tGood.service.ITGoodService;
import com.ruoyi.project.bajiaostar.tGoodDetail.domain.TGoodDetail;
import com.ruoyi.project.bajiaostar.tGoodDetail.service.ITGoodDetailService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 用户端登文件
 *
 */
@Slf4j
@RestController
@RequestMapping("/nt/file")
public class WebFilerController extends BaseController {

    @Autowired
    ITGoodService goodService;
    @Autowired
    ITGoodDetailService goodDetailService;



    @ApiOperation("下载文件模版")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @GetMapping("/downloadExcel")
    public void downloadExcel ( HttpServletResponse response) {
        //下载模板
        //方法一：直接下载路径下的文件模板（这种方式貌似在SpringCloud和Springboot中，打包成JAR包时，无法读取到指定路径下面的文件，不知道记错没，你们可以自己尝试下！！！）
        try {
            //文件名称
            String fileName = "goodTemplate.xlsx";
            //设置要下载的文件的名称
            response.setHeader("Content-disposition", "attachment;fileName=" + fileName);
            //通知客服文件的MIME类型
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            //获取文件的路径
            String downloadFilePath="";
           //String filePath = "/www/wwwroot/file/"+fileName;
            String filePath = "F:\\util-project\\2024\\zhengkai3\\basis_frame\\src\\main\\resources\\static\\file\\"+fileName;
            FileInputStream input = new FileInputStream(filePath);
            OutputStream out = response.getOutputStream();
            byte[] b = new byte[2048];
            int len;
            while ((len = input.read(b)) != -1) {
                out.write(b, 0, len);
            }
            //修正 Excel在“xxx.xlsx”中发现不可读取的内容。是否恢复此工作薄的内容？如果信任此工作簿的来源，请点击"是"
            response.setHeader("Content-Length", String.valueOf(input.getChannel().size()));
            input.close();
        } catch (Exception ex) {
            log.error("下载模版失败！！！{}",ex);
           throw new RuntimeException("模版下载失败");
        }
    }


    /**
     * 导入数据
     */
    @PostMapping("/importExcel")
    @UserRepeatSubmit
    public AjaxResult importData(String goodName,String goodFileUrl, MultipartFile file) {
        try {

            List<ImportGoodDto> lst = addDataStandardsByExcel(file);
            //保存项目名称
            TGood goods=new TGood();
            goods.setGoodName(goodName);
            goods.setGoodStatus(0);
            goods.setGoodFileUrl(goodFileUrl);
            int i = goodService.insertTGood(goods);
            if(i < 1){
                return AjaxResult.error("保存失败");
            }
            //模拟导入数据库操作
            for (ImportGoodDto in : lst) {
                TGoodDetail detail=new TGoodDetail();
                detail.setGoodId(goods.getId());
                detail.setGoodDate(in.getGoodDate());
                detail.setWeek(in.getWeek());
                detail.setTicketPrice(in.getTicketPrice());
                detail.setParagraph(in.getParagraph());
                detail.setGoodRow(in.getGoodRow());
                detail.setSeatNumber(in.getSeatNumber());
                detail.setInventory(in.getInventory());
                detail.setPrice(in.getPrice());
                detail.setDefaultSettlementPrice(in.getDefaultSettlementPrice());
                detail.setMemberSettlementPrice(in.getMemberSettlementPrice());
                detail.setDisplayInventory(in.getDisplayInventory());
                detail.setTwoMemberSettlementPrice(in.getTwoMemberSettlementPrice());
                detail.setGoodRemark(in.getGoodRemark());
                detail.setColour(in.getColour());
                detail.setPriceColour(in.getPriceColour());
                goodDetailService.insertTGoodDetail(detail);
            }
            return AjaxResult.success();
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }


    /**
     * 解析execl数据
     * @param file
     * @return
     * @throws IOException
     */
    public List<ImportGoodDto> addDataStandardsByExcel(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
//        初始化变量
        List<ImportGoodDto> dsmList = new ArrayList<>();
        InputStream is = file.getInputStream();
//        检查文件格式是否正确
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
//            自定义异常处理
            throw new RuntimeException("检查文件格式是否正确");
        }
        Workbook workbook = null;
        try {
            // 判断文件是2003格式的Excel还是2007格式的Excel
            boolean isExcel2003 = true;
            if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
                isExcel2003 = false;
            }
//        创建workbook对象
            workbook = null;
            if (isExcel2003) {
                workbook = new HSSFWorkbook(is);
            } else {
                workbook = new XSSFWorkbook(is);
            }
//        获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);
//        判断是否为空
            if (sheet == null) {
                throw new RuntimeException("内容为空");
            }
//        遍历工作表的每一行
            for (int i = 2; i <= Objects.requireNonNull(sheet).getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                // 检查行是否为空
                if (row == null) {
                    continue; // 如果为空，跳过该行
                }
                ImportGoodDto dsm = new ImportGoodDto();
                Object d1 =getCellValue( row.getCell(0));
                Object colour = getCellValue( row.getCell(1));
                Object d2 = getCellValue( row.getCell(1+1));
                Object d3 = getCellValue( row.getCell(2+1));
                Object priceColour = getCellValue( row.getCell(4));
                Object d4 = getCellValue( row.getCell(3+2));
                Object d5 = getCellValue( row.getCell(4+2));
                Object d6 = getCellValue( row.getCell(5+2));
                Object d7 = getCellValue( row.getCell(6+2));
                Object d8 = getCellValue( row.getCell(7+2));
                Object d9 = getCellValue( row.getCell(8+2));
                Object d10 = getCellValue( row.getCell(9+2));
                Object d11 = getCellValue( row.getCell(10+2));
                Object d12 = getCellValue( row.getCell(11+2));
                Object d13 = getCellValue( row.getCell(12+2));
                System.out.println("数据开始");
                System.out.println("d1="+d1);
                System.out.println("d2="+d2);
                System.out.println("d3="+d3);
                System.out.println("d4="+d4);
                System.out.println("d6="+d6);
                System.out.println("d7="+d7);
                System.out.println("d8="+d8);
                System.out.println("d9="+d9);
                System.out.println("d10="+d10);
                System.out.println("d11="+d11);
                System.out.println("d12="+d12);
                System.out.println("d13="+d13);
                System.out.println("数据结束");
                if(ObjectUtils.isEmpty(d1) || ObjectUtils.isEmpty(d2) || ObjectUtils.isEmpty(d3) ||ObjectUtils.isEmpty(d4) ||ObjectUtils.isEmpty(d5) ||ObjectUtils.isEmpty(d6) ||
                        ObjectUtils.isEmpty(d7) ||ObjectUtils.isEmpty(d8) ||ObjectUtils.isEmpty(d9) ||ObjectUtils.isEmpty(d10) ||ObjectUtils.isEmpty(d11) ||ObjectUtils.isEmpty(d12) ){
                    continue;
                }
                if((d1+"").contains("-")){
                    dsm.setGoodDate(DateUtils.parseDate(d1+"",DateUtils.YYYY_MM_DD));
                }else if((d1+"").contains("/")){
                    dsm.setGoodDate(DateUtils.parseDate(d1+"","yyyy/MM/dd"));
                }else {
                    if (d1 instanceof Date) {
                        Date date = (Date) d1;
                        // 使用date
                        dsm.setGoodDate(date);
                    }
                }
                if(!ObjectUtils.isEmpty(colour)){
                    dsm.setColour(colour+"");
                }
                dsm.setWeek(d2+"");
                dsm.setTicketPrice(Double.valueOf(d3+""));
                if(!ObjectUtils.isEmpty(priceColour)){
                    dsm.setPriceColour(priceColour+"");
                }
                if(isNumeric(d4+"")){
                    dsm.setParagraph(new BigDecimal(d4+"").intValue()+"");
                }else{
                    dsm.setParagraph(d4+"");
                }
                if(isNumeric(d5+"")){
                    dsm.setGoodRow(new BigDecimal(d5+"").intValue()+"");
                }else{
                    dsm.setGoodRow(d5+"");
                }
                dsm.setSeatNumber(d6+"");
                dsm.setInventory(new BigDecimal(d7+"").longValue());
                dsm.setDisplayInventory(new BigDecimal(d8+"").longValue());
                dsm.setPrice(Double.valueOf(d9+""));
                dsm.setDefaultSettlementPrice(Double.valueOf(d10+""));
                dsm.setMemberSettlementPrice(Double.valueOf(d11+""));
                dsm.setTwoMemberSettlementPrice(Double.valueOf(d12+""));
                if(!ObjectUtils.isEmpty(d13)){
                    dsm.setGoodRemark(d13+"");
                }
                dsmList.add(dsm);
            }
            is.close();
            return dsmList;
        } catch (Exception e) {
            // 处理文件读取异常
            e.printStackTrace(); // 这里可以记录日志或者返回相应错误信息
            throw new RuntimeException("文件读取异常，无法进行数据导入");
        } finally {
            // 确保关闭流
            if (workbook != null) {
                workbook.close();
            }
            is.close();
        }
    }

    /**
     * 判断是否数字
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        try {
            Double.parseDouble(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /*
     * @description: 获取单元格的值 <br>
     * @create: 2023/9/20 16:47 <br>
     * @param cell
     * @return java.lang.Object
     */
    private static Object getCellValue(Cell cell){
        if(cell == null){
            return null;
        }
        int cellType = cell.getCellType();
        if(cellType==CellType.BLANK.getCode()){
            return null;
        }
        //字符串
        if (cellType==CellType.STRING.getCode()){
            return cell.getStringCellValue();
        }
        if(cellType==CellType.NUMERIC.getCode()){
            //日期
            if(HSSFDateUtil.isCellDateFormatted(cell)){
                return cell.getDateCellValue();
            }else{
                //数值
                return cell.getNumericCellValue();
            }
        }
        //布尔
        if(cellType==CellType.BOOLEAN.getCode()){
            return cell.getBooleanCellValue();
        }
        return null;
    }

    /**
     * 导入数据(编辑导入)
     */
    @PostMapping("/updateImportExcel")
    @UserRepeatSubmit
    public AjaxResult importData(String goodName,Long goodId,String goodFileUrl, MultipartFile file) {
        try {
            if(ObjectUtils.isEmpty(goodId)){
                return AjaxResult.error("更新标识不能为空");
            }
            if(!ObjectUtils.isEmpty(goodName)){
                TGood good=new TGood();
                good.setId(goodId);
                good.setGoodName(goodName);
                good.setGoodFileUrl(goodFileUrl);
                goodService.updateTGood(good);
            }
            if(ObjectUtils.isEmpty(file)){
                return AjaxResult.success();
            }
            //根据商品id修改所有商品为不可用
            goodDetailService.updateGoodDetailStatusByGoodId(goodId);
            //获取文件的输入流
            List<UpdateImportExcelDto> lst = updateDataStandardsByExcel(file);
            //模拟导入数据库操作
            for (UpdateImportExcelDto in : lst) {
                TGoodDetail detail=new TGoodDetail();
                //detail.setId(in.getId());
                detail.setGoodDate(in.getGoodDate());
                detail.setWeek(in.getWeek());
                detail.setTicketPrice(in.getTicketPrice());
                detail.setParagraph(in.getParagraph());
                detail.setGoodRow(in.getGoodRow());
                detail.setSeatNumber(in.getSeatNumber());
                detail.setInventory(in.getInventory());
                detail.setPrice(in.getPrice());
                detail.setDefaultSettlementPrice(in.getDefaultSettlementPrice());
                detail.setMemberSettlementPrice(in.getMemberSettlementPrice());
                detail.setDisplayInventory(in.getDisplayInventory());
                detail.setTwoMemberSettlementPrice(in.getTwoMemberSettlementPrice());
                detail.setGoodRemark(in.getGoodRemark());
                detail.setGoodId(goodId);
                detail.setColour(in.getColour());
                detail.setPriceColour(in.getPriceColour());
               // detail.setGoodSort(in.getGoodSort());
                goodDetailService.insertTGoodDetail(detail);
               /* if(ObjectUtils.isEmpty(in.getId())){
                    detail.setGoodId(goodId);
                    goodDetailService.insertTGoodDetail(detail);
                }else{
                    goodDetailService.updateTGoodDetail(detail);
                }*/

            }
            return AjaxResult.success();
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }

    /**
     * 解析execl数据
     * @param file
     * @return
     * @throws IOException
     */
    public List<UpdateImportExcelDto> updateDataStandardsByExcel(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
//        初始化变量
        List<UpdateImportExcelDto> dsmList = new ArrayList<>();
        InputStream is = file.getInputStream();
//        检查文件格式是否正确
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
//            自定义异常处理
            throw new RuntimeException("检查文件格式是否正确");
        }
        Workbook workbook = null;
        try {
            // 判断文件是2003格式的Excel还是2007格式的Excel
            boolean isExcel2003 = true;
            if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
                isExcel2003 = false;
            }
//        创建workbook对象
            workbook = null;
            if (isExcel2003) {
                workbook = new HSSFWorkbook(is);
            } else {
                workbook = new XSSFWorkbook(is);
            }
//        获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);
//        判断是否为空
            if (sheet == null) {
                throw new RuntimeException("内容为空");
            }
//        遍历工作表的每一行
            for (int i = 1; i <= Objects.requireNonNull(sheet).getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                // 检查行是否为空
                if (row == null) {
                    continue; // 如果为空，跳过该行
                }
                UpdateImportExcelDto dsm = new UpdateImportExcelDto();
                //Object id =getCellValue( row.getCell(0));
                Object d1 =getCellValue( row.getCell(1-1));
                Object colour = getCellValue( row.getCell(1));
                Object d2 = getCellValue( row.getCell(2));
                Object d3 = getCellValue( row.getCell(3));
                Object priceColour = getCellValue( row.getCell(4));
                Object d4 = getCellValue( row.getCell(4+1));
                Object d5 = getCellValue( row.getCell(5+1));
                Object d6 = getCellValue( row.getCell(6+1));
                Object d7 = getCellValue( row.getCell(7+1));
                Object d8 = getCellValue( row.getCell(8+1));
                Object d9 = getCellValue( row.getCell(9+1));
                Object d10 = getCellValue( row.getCell(10+1));
                Object d11 = getCellValue( row.getCell(11+1));
                Object d12 = getCellValue( row.getCell(12+1));
                Object d13 = getCellValue( row.getCell(13+1));
                System.out.println("数据开始");
                //System.out.println("id="+id);
                System.out.println("d1="+d1);
                System.out.println("d2="+d2);
                System.out.println("d3="+d3);
                System.out.println("d4="+d4);
                System.out.println("d6="+d6);
                System.out.println("d7="+d7);
                System.out.println("d8="+d8);
                System.out.println("d9="+d9);
                System.out.println("d10="+d10);
                System.out.println("d11="+d11);
                System.out.println("d12="+d12);
                System.out.println("d13="+d13);
                System.out.println("数据结束");
                if( ObjectUtils.isEmpty(d2) || ObjectUtils.isEmpty(d3) ||ObjectUtils.isEmpty(d4) ||ObjectUtils.isEmpty(d5) ||ObjectUtils.isEmpty(d6) ||
                        ObjectUtils.isEmpty(d7) ||ObjectUtils.isEmpty(d8) ||ObjectUtils.isEmpty(d9) ||ObjectUtils.isEmpty(d10) ||ObjectUtils.isEmpty(d11) ||ObjectUtils.isEmpty(d12) ){
                    continue;
                }

                if((d1+"").contains("-")){
                    dsm.setGoodDate(DateUtils.parseDate(d1+"",DateUtils.YYYY_MM_DD));
                }else if((d1+"").contains("/")){
                    dsm.setGoodDate(DateUtils.parseDate(d1+"","yyyy/MM/dd"));
                }else {
                    if (d1 instanceof Date) {
                        Date date = (Date) d1;
                        // 使用date
                        dsm.setGoodDate(date);
                    }
                }
                dsm.setWeek(d2+"");
                dsm.setTicketPrice(Double.valueOf(d3+""));
                if(!ObjectUtils.isEmpty(priceColour)){
                    dsm.setPriceColour(priceColour+"");
                }
                if(isNumeric(d4+"")){
                    dsm.setParagraph(new BigDecimal(d4+"").intValue()+"");
                }else{
                    dsm.setParagraph(d4+"");
                }
                if(isNumeric(d5+"")){
                    dsm.setGoodRow(new BigDecimal(d5+"").intValue()+"");
                }else{
                    dsm.setGoodRow(d5+"");
                }
                if(!ObjectUtils.isEmpty(colour)){
                    dsm.setColour(colour+"");
                }
                dsm.setSeatNumber(d6+"");
                dsm.setInventory(new BigDecimal(d7+"").longValue());
                dsm.setDisplayInventory(new BigDecimal(d8+"").longValue());
                dsm.setPrice(Double.valueOf(d9+""));
                if(!ObjectUtils.isEmpty(priceColour)){
                    dsm.setPriceColour(priceColour+"");
                }
                dsm.setDefaultSettlementPrice(Double.valueOf(d10+""));
                dsm.setMemberSettlementPrice(Double.valueOf(d11+""));
                dsm.setTwoMemberSettlementPrice(Double.valueOf(d12+""));
                if(!ObjectUtils.isEmpty(d13)){
                    dsm.setGoodRemark(d13+"");
                }
                dsmList.add(dsm);
            }
            is.close();
            return dsmList;
        } catch (Exception e) {
            // 处理文件读取异常
            e.printStackTrace(); // 这里可以记录日志或者返回相应错误信息
            throw new RuntimeException("文件读取异常，无法进行数据导入");
        } finally {
            // 确保关闭流
            if (workbook != null) {
                workbook.close();
            }
            is.close();
        }
    }
}
